# coding=utf-8
from datetime import time
from gm.api import *
from quant.data import juejin
from sys import platform
import click
import logging
import pathlib
import requests


def start_sub(context):
    context.dominant, context.sub_dominant = juejin.get_dominants(
        context.now.date())
    logging.info('%s %s' % (context.dominant, context.sub_dominant))
    subscribe([context.dominant, context.sub_dominant, context.zz500],
              frequency=context.freq, wait_group=True, unsubscribe_previous=True)


def init(context):
    context.zz500 = 'SHSE.000905'
    context.price_map = {}
    context.counter = 0
    schedule(schedule_func=start_sub, date_rule='1d', time_rule='09:30:00')
    if context.mode == MODE_LIVE:
        context.freq = 'tick'
        if context.now.time() > time(9, 30, 0):
            start_sub(context)
    else:
        context.freq = '60s'


def notify(msg):
    url = 'https://api2.pushdeer.com/message/push?pushkey=%s&text=%s' % (
        'PDU1973TWsDuoG8zdW9G7K9uZzym5G5rywuc2VEw', msg)
    proxies = {
        'http': '',
        'https': '',
    }
    try:
        requests.get(url, proxies=proxies)
    except Exception as e:
        logging.error(e)


def on_price_update(context, symbol, price):
    context.price_map[symbol] = price
    if context.dominant in context.price_map and context.sub_dominant in context.price_map and context.zz500 in context.price_map:
        dom = context.price_map[context.dominant]
        sub_dom = context.price_map[context.sub_dominant]
        zz500 = context.price_map[context.zz500]
        if context.counter % 100 == 0:
            msg = '{}: {:.2f}, {:.2f}, {:.2f}'.format(
                context.now, dom - zz500, sub_dom - zz500, sub_dom - dom)
            logging.info(msg)
            # notify(msg)
    context.counter += 1


def on_tick(context, tick):
    on_price_update(context, tick.symbol, tick.price)


def on_bar(context, bars):
    for bar in bars:
        on_price_update(context, bar.symbol, bar.close)


if __name__ == '__main__':
    '''
        strategy_id策略ID, 由系统生成
        filename文件名, 请与本文件名保持一致
        mode运行模式, 实时模式:MODE_LIVE回测模式:MODE_BACKTEST
        token绑定计算机的ID, 可在系统设置-密钥管理中生成
        backtest_start_time回测开始时间
        backtest_end_time回测结束时间
        backtest_adjust股票复权方式, 不复权:ADJUST_NONE前复权:ADJUST_PREV后复权:ADJUST_POST
        backtest_initial_cash回测初始资金
        backtest_commission_ratio回测佣金比例
        backtest_slippage_ratio回测滑点比例
        '''
    import logging
    logging.getLogger().setLevel(logging.INFO)
    if platform == 'linux':
        serv_addr = 'www.xn--4gqp3kj4hgvhbnaj0m7o1g.cn:7001'
        filename = pathlib.Path(__file__).stem
    else:
        serv_addr = '127.0.0.1:7001'
        filename = 'main.py'
    logging.info(serv_addr)
    run(strategy_id='62368bb8-d592-11ec-8fee-0022486c3262',
        filename=filename,
        mode=MODE_BACKTEST,
        token='567120cd2f9b2ce8ae3fbd7ee76ed06bf899b512',
        backtest_start_time='2022-05-01 08:00:00',
        backtest_end_time='2022-05-18 16:00:00',
        backtest_adjust=ADJUST_PREV,
        backtest_initial_cash=10000000,
        backtest_commission_ratio=0.0001,
        backtest_slippage_ratio=0.0001,
        serv_addr=serv_addr)
